package droid.frame.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

/**
 * ImageView(正方形)<br>
 * （即是:高度/宽度==1, 高度决定宽度） 注意是根据高度计算宽度
 * 
 * @author coffee <br>
 *         2016-10-20下午5:21:11
 */
@SuppressLint("AppCompatCustomView")
public class SquareImageView extends ImageView {
	private int viewWidth = 0;//
	private int viewHeight = 0;

	private int maxHeight = 0;

	public SquareImageView(Context context) {
		super(context);
	}
	@SuppressWarnings("ResourceType")
	public SquareImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		int[] arr = new int[] { android.R.attr.layout_width, android.R.attr.layout_height, android.R.attr.maxHeight };
		TypedArray typedArray = context.obtainStyledAttributes(attrs, arr);
		// MATCH_PARENT -1 WRAP_CONTENT-2
		try {
			TypedValue maxHeightValue = typedArray.peekValue(2);
			// 没设置maxHeight
			if (maxHeightValue == null) {
				// 不做处理
			} else {
				maxHeight = TypedValue.complexToDimensionPixelSize(maxHeightValue.data, getResources().getDisplayMetrics());
			}
		} catch (Exception e) {
			// java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x10
			e.printStackTrace();
		}
		typedArray.recycle();
	}

	/**
	 * 处理高度、不能大于maxHeight
	 * 
	 * @return
	 */
	private int getCorrectHeight() {
		int measuredHeight = getMeasuredHeight();
		if (measuredHeight > maxHeight) {
			measuredHeight = maxHeight;
		}
		return measuredHeight;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
		viewHeight = getCorrectHeight() + getPaddingTop() + getPaddingBottom();
		// 屏幕的宽度根据组件
		viewWidth = viewHeight;
		if (viewWidth > 0) {
			// Log.d("image:scale", imageWidth + "," + imageHeight + " -- " + viewWidth + "," + viewHeight);
			widthMeasureSpec = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.EXACTLY);
			// 精确计算高度
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}
